package cn.itcast.bos.web.action.base;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Actions;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;

import cn.itcast.bos.domain.base.Standard;
import cn.itcast.bos.service.base.StandardService;
@ParentPackage("json-default")
@Namespace("/")
@Actions
@Controller
@Scope("prototype")
public class StandardAction extends ActionSupport implements ModelDriven<Standard>{

	private Standard standard=new Standard();
	
	@Override
	public Standard getModel() {
		return standard;
	}
	
	//使用属性驱动,获取page与cows两个参数的值
	private int page;
	private int rows;
	
	public void setPage(int page) {
		this.page = page;
	}
	public void setRows(int rows) {
		this.rows = rows;
	}

	@Autowired
	private StandardService standardService;
	
	@Action(value="standard_save", results={@Result(type="redirect",location="./pages/base/standard.html")})
	public String save(){
		standardService.save(standard);
		return SUCCESS;
	}
	
	//分页列表查询
	@Action(value="standard_pageQuery",results={@Result(name="success",type="json")})
	public String pageQuery(){
		
		System.out.println(page);
		
		//调用业务层,查询数据结果
		Pageable pageable=new PageRequest(page-1,rows);
		Page<Standard> pageData=standardService.findPageData(pageable);
		
		//返回客户数据,需要total和rows
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("total", pageData.getTotalElements());		//getNumberOfElements()获得的是当前页的数据总数
		map.put("rows", pageData.getContent());
		
		//将map转为json返回,使用Spring-json-plugin插件
		ActionContext.getContext().getValueStack().push(map);
		return SUCCESS;
	}
	
	//查询所有取派标准名称
	@Action(value="standard_list",results={@Result(type="json")})
	public String list(){
		List<Standard> list=standardService.list();
		ActionContext.getContext().getValueStack().push(list);
		return SUCCESS;
	}

}
